import store from "@/vuex/store.js"
import {createXHR} from "@/common/js/base/createXHR.js"
import router from '@/router/index.js'

var server = store.state.ip + "/card/create";//服务器地址
import $ from "jquery"



function getBase64Image(img) {
  var imgs = document.createElement("img");
  imgs.src = img;
  var canvas = document.createElement("canvas"), //创建canvas元素
    width = imgs.width, //确保canvas的尺寸和图片一样
    height = imgs.height;
  canvas.width = width;
  canvas.height = height;
  canvas.getContext("2d").drawImage(imgs, 0, 0, width, height); //将图片绘制到canvas中
  var dataURL = canvas.toDataURL('image/jpeg'); //转换图片为dataURL
  return dataURL
}


function dataURItoBlob(base64Data) {
  var byteString;
  if (base64Data.split(',')[0].indexOf('base64') >= 0)
    byteString = atob(base64Data.split(',')[1]);
  else
    byteString = unescape(base64Data.split(',')[1]);
  var mimeString = base64Data.split(',')[0].split(':')[1].split(';')[0];
  var ia = new Uint8Array(byteString.length);
  for (var i = 0; i < byteString.length; i++) {
    ia[i] = byteString.charCodeAt(i);
  }
  return new Blob([ia], {type: mimeString});
}




// 上传文件
let imgUrl = null;
function upload(title,content,center,centers) {
  upload1(title,content,center,centers);
  // uploads(,imgUrl);
}

function getNowFormatDate() {//获取时间
  var date = new Date();
  var seperator1 = "-";
  var seperator2 = ":";
  var month = date.getMonth() + 1;
  var strDate = date.getDate();
  if (month >= 1 && month <= 9) {
    month = "0" + month;
  }
  if (strDate >= 0 && strDate <= 9) {
    strDate = "0" + strDate;
  }
  var currentdate = date.getFullYear() + seperator1 + month + seperator1 + strDate
    + " " + date.getHours() + seperator2 + date.getMinutes()
    + seperator2 + date.getSeconds();
  return currentdate;
}

function upload1(title,content,center,centers) {     //上传投送卡封面图
  if(store.state.issueCover===null){
    plus.nativeUI.toast("请拍摄标题图");
    return false
  }
  var formData = new FormData();
  var blob = dataURItoBlob(getBase64Image(store.state.issueCover));
  formData.append("image/png", blob, "image.png");
  formData.append("fileType",1);
  var xhr = createXHR();
  xhr.onreadystatechange = function () {
    if((xhr.status>=200&&xhr.status<300)||xhr.status == 304){
      let imgUrl = JSON.parse(xhr.responseText).data;
      uploads(title,content,center,centers,imgUrl);
      store.commit("issueCover",null)
    }
  };
  xhr.open('POST',store.state.ip + "/card/upload", false);
  xhr.setRequestHeader("authorization", localStorage.userid + "_" + store.state.token);
  xhr.send(formData);
}

function uploads(title,content,center,centers,url) {   //提交投送卡参数
  var data = {
    "userID": localStorage.userid,
    "title": title,
    "userLat": center.lat,
    "userLng": center.lng,
    "cardPic":url,
    // "deliverTime":getNowFormatDate(),
    "cardContents": [
      {"text": content}
    ],
    "cardDelivers": centers
  };
  $.ajax({
    type: "post",
    url: server,
    datatype: 'json',
    data: JSON.stringify(data),
    cache: false,
    traditional: true,
    contentType: false,
    processData: false,
    beforeSend: function (request) {
      request.setRequestHeader("authorization", localStorage.userid + "_" + store.state.token);
      request.setRequestHeader("Content-Type", "application/json;charset=UTF-8")
    },
    success: function (result) {
      store.commit('issueCover', null);
      console.log(result)
      router.push({path: '/chat'});
    }, error: function (XMLHttpRequeset, textStatus, errorThrown) {
      store.commit('issueCover', null);
      console.log(XMLHttpRequeset, textStatus, errorThrown)
    }
  });
}
export default {
  upload
}
